import * as dayjs from "dayjs";
import { concatMap, delay, Observable, of, range } from "rxjs";

type Loggable = string | number | boolean;
export function getLogger(name: string) {
    const el = document.createElement("div");
    el.style.marginBottom = "20px";
    document.body.appendChild(el);
    console.assert(el, "el falsy");
    const line = (text: Loggable) => {
        const l = document.createElement("div");
        l.innerText = text.toString();
        return l;
    }
    const log = (...ls: Loggable[]) => {
        const frag = document.createDocumentFragment();
        const header = line(`[${name.toUpperCase()}]`);
        header.style.fontWeight = "bold";
        header.style.color = "blue";
        frag.appendChild(header);
        ls.forEach(e => frag.appendChild(line(e)));
        el.innerHTML = "";
        el.appendChild(frag);
    }
    log("");
    return log;
}

export function getCountingLogger(name: string) {
    let count = 0;
    const logger = getLogger(name);
    return (s: string) => {
        count++;
        logger(`count:${count}, ${s}`);
    }
}

export const ts = () => dayjs().format("HH:mm:ss.SSS");

export function randomInterval(varianceMs = 2000): Observable<number> {
    return range(1, 1000000).pipe(
        concatMap(i => of(i).pipe(delay(100 + Math.ceil(Math.random() * varianceMs)))),
    );
}
